
import importlib
from typing import Any
import inspect
import asyncio

class ImportFromStringError(Exception):
    pass


def import_from_string(import_str: Any) -> Any:
    if not isinstance(import_str, str):
        return import_str

    module_str, _, attrs_str = import_str.partition(":")
    print(module_str, _, attrs_str,)
    if not module_str or not attrs_str:
        message = 'Import string "{import_str}" must be in format "<module>:<attribute>".'
        raise ImportFromStringError(message.format(import_str=import_str))

    try:
        module = importlib.import_module(module_str)
    except ModuleNotFoundError as exc:
        if exc.name != module_str:
            raise exc from None
        message = 'Could not import module "{module_str}".'
        raise ImportFromStringError(message.format(module_str=module_str))

    instance = module
    try:
        for attr_str in attrs_str.split("."):
            instance = getattr(instance, attr_str)
    except AttributeError:
        message = 'Attribute "{attrs_str}" not found in module "{module_str}".'
        raise ImportFromStringError(message.format(attrs_str=attrs_str, module_str=module_str))

    return instance


app = "测试string调用:App"
# app = "测试string调用:"
# app = []
loaded_app = import_from_string(app)
loaded_app = loaded_app()
loaded_app.print_count()
loaded_app.print_count()
loaded_app.print_count()

if inspect.isclass(loaded_app):
    use_asgi_3 = hasattr(loaded_app, "__await__")
    print("--------1------------------")
elif inspect.isfunction(loaded_app):
    use_asgi_3 = asyncio.iscoroutinefunction(loaded_app)
    print("---------2-----------------")
else:
    call = getattr(loaded_app, "__call__", None)
    use_asgi_3 = asyncio.iscoroutinefunction(call)
    print("----------3----------------")

interface = "asgi3" if use_asgi_3 else "asgi2"
print("interface:  ", interface)